import { _decorator, Component, Node, director, assetManager, Sprite, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('StartGame')
export class StartGame extends Component {

    clickStart: boolean = false

    @property(Node) startGameBtn: Node
    @property(Node) loadBundleProgressBar: Node

    start() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    update(deltaTime: number) {

    }

    onTouchStart() {
        this.clickStart = true
    }

    onTouchEnd() {
        if (!this.clickStart) {
            return
        }

        const bar = this.loadBundleProgressBar.getChildByName('ProgressBar').getChildByName('Bar')
        const finishedLabel = this.loadBundleProgressBar.getChildByName('标题').getChildByName('左')
        const totalLabel = this.loadBundleProgressBar.getChildByName('标题').getChildByName('右')
        bar.getComponent(Sprite).fillRange = 0

        this.startGameBtn.active = false
        this.loadBundleProgressBar.active = true

        assetManager.loadBundle('res', (err, bundle) => {
            if (err) {
                return console.error(err);
            }
            console.log('load bundle successfully.');
            bundle.preloadScene('game', (finished: number, total: number, item: any) => {
                // console.log(finished, total);
                finishedLabel.getComponent(Label).string = String(finished)
                totalLabel.getComponent(Label).string = String(total)
                bar.getComponent(Sprite).fillRange = finished / total
            }, (err) => {
                if (err) {
                    return console.error(err);
                }
                console.log('load bundleScene successfully.');
                director.loadScene('game')
                this.clickStart = true
            })

        });
    }
}


